#include <pthread.h>
#include <iostream>
#include "threadcancel.h"

void* startCancelableCounterthread(void* args) {
    int oldState;
    int* j = new int;

    pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, &oldState);  /* Thread-cancelling is
                                                                   enabled */
    ThreadData data = *(ThreadData *) args;
    *j = data.max;
    for (int i = 0; i < data.max; i++) {
        std::cout << data.name << ": " << i << std::endl;
        usleep(data.delay);
        pthread_testcancel();   // Test for a pending cancel-signal
        if (i == 8) {
            std::cout << "Exiting Thread" << std::endl;
            pthread_exit (j);   // Equivalent to return j
        }
    }
    return j;
}